import React, { useEffect } from 'react';

function ajax(url) {
  return new Promise(function (resolve, reject) {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url);
    xhr.responseType = 'json';
    xhr.onload = function () {
      if (this.status === 200) {
        resolve(this.responseType);
      } else {
        reject(new Error(this.statusText));
      }
    };
    xhr.send();
  });
}

export default function PromiseDemo() {
  useEffect(() => {
    ajax('http://localhost:3001/api/ajax')
      .then(function (res) {
        console.log(res);
        return ajax('/error/url');
      })
      .catch(e => {
        console.log(e);
      });
  }, []);

  return (
    <div>
      <p>Promise 常见误区</p>
    </div>
  );
}
